<style lang="stylus" scoped>

</style>

<template>
  <div>
    <q-table
      class="bg-white shadow-1"
      :data="data"
      dense
      :columns="columns"
      row-key="id"
      separator="cell"
      selection="multiple"
      :selected.sync="selected"
      :visible-columns="visibleColumns"
      :filter="searchForm"
      :pagination.sync="pagination"
      :rows-per-page-options="[3, 5, 10, 20]"
      no-data-label="暂无数据"
      table-class="h-custom"
      @request="listGet"
    >
      <template v-slot:top-left="props">
        <q-btn size="sm" color="light-blue" :label="$t('新增')" @click="add"/>
        <!-- <q-btn color="negative" flat :label="$t('批量删除')" class="q-ml-sm"/> -->
      </template>
      <template v-slot:top-right="props">
        <q-select
          v-model="visibleColumns"
          multiple
          borderless
          options-dense
          :display-value="$t('显示列')"
          emit-value
          map-options
          :options="columns"
          option-value="name"
          class="q-mx-lg"
        >
          <template v-slot:option="scope">
            <q-item
              v-bind="scope.itemProps"
              v-on="scope.itemEvents"
              v-if="!scope.opt.required"
            >
              <q-item-section avatar>
                <q-toggle color="blue" v-model="visibleColumns" :val="scope.opt.name" />
              </q-item-section>
              <q-item-section style="min-width:60px">
                {{ scope.opt.label }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <q-toggle
          v-model="searchToggle"
          left-label
          label="搜索"
          color="blue"
          checked-icon="check"
          unchecked-icon="clear"
          keep-color
        />
        <q-btn
          flat round dense
          :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
          @click="props.toggleFullscreen"
          class="q-ml-md"
        />
      </template>
      <template v-if="searchToggle" v-slot:top-row="props">
        <q-tr :props="props">
          <q-td>
          </q-td>
          <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
            <q-btn color="primary" dense flat icon="search" class="absolute-center" v-if="col.name==='action'" @click="listGet({ pagination: pagination, filter: searchForm })"/>
            <q-input dense outlined v-model="searchForm[col.name]" v-else/>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th>
            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
          </q-th>
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td width="52">
            <q-checkbox dense v-model="props.selected" />
          </q-td>
          <q-td key="action" :props="props">
            <q-btn-dropdown
              color="blue"
              size="sm"
              dense
              menu-anchor="bottom left"
              menu-self="top left"
              content-class="text-grey"
              icon="settings">
              <q-list dense>
                <q-item clickable v-close-popup @click="edit(props.row)">
                  <q-item-section>
                    <q-item-label>修改</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="delRow(props.row)">
                  <q-item-section>
                    <q-item-label>删除</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="props.expand = !props.expand">
                  <q-item-section>
                    <q-item-label>{{ props.expand? '收起': '更多字段' }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>
          </q-td>
          <q-td key="name" :props="props">{{ props.row.name }}</q-td>
          <q-td key="code" :props="props">{{ props.row.code  }}</q-td>
          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
        </q-tr>
        <q-tr v-show="props.expand" :props="props">
          <q-td colspan="100%">
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="props">
        <q-pagination
          v-model="pagination.page"
          color="blue"
          :max-pages="5"
          :max="pages"
          :boundaryLinks="true"
          :directionLinks="true"
        />
        共 {{ total }} 条
      </template>
    </q-table>
    <q-dialog
      v-model="addOrEditDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white dailog relative-position" :style="{minWidth: addOrEditTab === 'tab1'?'40vw': '75vw'}">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addOrEdit === 1? '新增' : '修改'}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addOrEditDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <q-tabs
            v-model="addOrEditTab"
            dense
            class="text-grey-9"
            active-color="primary"
            indicator-color="primary"
            align="left"
            :breakpoint="0"
            narrow-indicator
          >
            <q-tab name="tab1" label="角色属性" />
            <q-tab name="tab2" label="权限" :disable="!addOrEditForm.id"/>
          </q-tabs>
          <q-separator />
          <q-tab-panels v-model="addOrEditTab" animated>
            <q-tab-panel name="tab1" class="row q-col-gutter-sm">
              <div class="col-12">
                <div :class="$v.addOrEditForm.code.$error?'text-negative': ''">角色编码</div>
                <q-input
                  v-model="addOrEditForm.code"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.code.$error"
                  @blur="$v.addOrEditForm.code.$touch"
                  dense hint :disable="addOrEdit !== 1"/>
              </div>
              <div class="col-12">
                <div :class="$v.addOrEditForm.name.$error?'text-negative': ''">角色名称</div>
                <q-input
                  v-model="addOrEditForm.name"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.name.$error"
                  @blur="$v.addOrEditForm.name.$touch"
                  dense hint/>
              </div>
              <div class="col-12">
                <q-checkbox v-model="addOrEditForm.defaultRole" :true-value="1" :false-value="0" label="新用户默认拥有此角色" color="light-blue"/>
              </div>
            </q-tab-panel>

            <q-tab-panel name="tab2" class="row relative-position">
              <div class="col-12">
                <q-chip dense>
                  <q-avatar icon="bookmark" color="light-blue" text-color="white" />
                    点击菜单树下叶子节点名称以分配按钮和字段权限
                </q-chip>
              </div>
              <div v-if="isNodeSelected" class="absolute-right" style="top:20px;right:42px;z-index:9">
                <q-btn color="light-blue" :loading="saveUserRoleGroupLoading" label="保存" @click="saveJurisdiction">
                  <q-tooltip anchor="top middle" self="bottom middle" :offset="[5, 5]" content-class="bg-black text-white">
                    <div style="width:150px;font-size:11px">
                      保存为当前岗位所分配的菜单和字段
                    </div>
                  </q-tooltip>
                </q-btn>
              </div>
              <!-- <div class="absolute-left" style="top:20px;left:42px;z-index:9"> -->
                <!-- <q-chip dense  class="absolute-left" style="top:20px;left:42px;z-index:9">
                  <q-avatar icon="bookmark" color="light-blue" text-color="white" />
                    点击菜单树下叶子节点名称以分配按钮和字段权限
                </q-chip> -->
              <!-- </div> -->
              <div :class="[isNodeSelected ? 'col-lg-4 col-md-4' : 'col-lg-12 col-md-12', 'col-sm-12 col-xs-12']" :style="maximizedToggle==false?'max-height:40vh;overflow:auto':''">
                <q-tree
                  color="light-blue"
                  :nodes="nodes"
                  node-key="id"
                  label-key="name"
                  ref="trees"
                  :selected.sync="nodeSelected"
                  selected-color="primary"
                  :expanded.sync="nodeExpanded"
                  tick-strategy="leaf"
                  :ticked.sync="nodeTicked"
                  default-expand-all
                >
                  <template v-slot:header-root="prop">
                    <div class="row items-center" style="width:100%;" id="treeName"  @click="nodeSelectedClick(prop.node.id)">
                      <q-badge transparent align="middle" color="primary">
                        菜单
                      </q-badge>
                      <div class="text-weight-bold ellipsis q-ml-xs" style="width:80%" :title="prop.node.kjCode + ' - ' + prop.node.name">{{ prop.node.kjCode + ' - ' + prop.node.name }}</div>
                    </div>
                  </template>
                  <template v-slot:header-header="prop">
                    <div class="row items-center" style="width:100%;flex-wrap:nowrap" @click="nodeSelectedClick(prop.node.id)">
                      <q-badge transparent align="middle" color="orange">
                        tab
                      </q-badge>
                      <div class="text-weight-bold ellipsis q-ml-xs" style="width:80%" :title="prop.node.name">{{ prop.node.name }}</div>
                    </div>
                  </template>
                </q-tree>
              </div>
              <div v-if="isNodeSelected" :class="[isNodeSelected ? 'col-lg-8 col-md-8' : '', 'col-sm-12 col-xs-12']">
                <q-stepper
                  v-model="step"
                  vertical
                  flat
                  color="light-blue"
                  active-color="light-blue"
                  animated
                >
                  <q-step
                    :name="1"
                    title="按钮"
                    icon="fas fa-user-tag"
                    active-icon="fas fa-user-tag"
                    @click="step = 1"
                  >
                    <q-table
                      flat
                      dense
                      class="bg-white"
                      :data="dataButtom"
                      :columns="columnsButtom"
                      :hide-bottom="dataButtom.length!=0"
                      row-key="id"
                      separator="cell"
                      selection="multiple"
                      :selected.sync="selectedButtom"
                      :filter="searchFormButtom"
                      :pagination.sync="paginationButtom"
                      :rows-per-page-options="[40, 50, 60, 80]"
                      no-data-label="暂无数据"
                      table-class="h-custom"
                    >
                      <template v-slot:header="props">
                        <q-tr :props="props" style="height:36px">
                          <q-th>
                            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
                          </q-th>
                          <q-th v-for="col in props.cols" :key="col.name" :props="props">
                            {{ col.label }}
                          </q-th>
                        </q-tr>
                      </template>
                      <template v-slot:body="props">
                        <q-tr :props="props" style="height:36px">
                          <q-td width="52">
                            <q-checkbox dense v-model="props.selected" />
                          </q-td>
                          <q-td key="name" :props="props">{{ props.row.name }}</q-td>
                          <q-td key="code" :props="props">{{ props.row.code  }}</q-td>
                          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
                        </q-tr>
                        <q-tr v-show="props.expand" :props="props">
                          <q-td colspan="100%">
                          </q-td>
                        </q-tr>
                      </template>
                      <template v-slot:pagination="props">
                        <!-- <q-pagination
                          v-model="paginationRole.page"
                          color="blue"
                          :max-pages="5"
                          :max="pagesRole"
                          :boundaryLinks="true"
                          :directionLinks="true"
                        /> -->
                        <q-pagination
                          v-model="paginationButtom.page"
                          :max="pagesButtom"
                          :input="true"
                        >
                        </q-pagination>
                        共 {{ totalButtom }} 条
                      </template>
                    </q-table>
                  </q-step>
                  <q-step
                    :name="2"
                    title="字段"
                    icon="fas fa-user-tag"
                    active-icon="fas fa-user-tag"
                    @click="step = 2"
                  >
                  <q-table
                      flat
                      dense
                      class="bg-white"
                      :data="dataField"
                      :columns="columnsField"
                      row-key="id"
                      separator="cell"
                      selection="multiple"
                      :selected.sync="selectedField"
                      :filter="searchFormField"
                      :pagination.sync="paginationField"
                      :rows-per-page-options="[40, 50, 60, 80]"
                      :hide-bottom="dataField.length!=0"
                      no-data-label="暂无数据"
                      table-class="h-custom"
                    >
                      <template v-slot:header="props">
                        <q-tr :props="props" style="height:36px">
                          <q-th>
                            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
                          </q-th>
                          <q-th v-for="col in props.cols" :key="col.name" :props="props">
                            {{ col.label }}
                          </q-th>
                        </q-tr>
                      </template>
                      <template v-slot:body="props">
                        <q-tr :props="props" style="height:36px">
                          <q-td width="52">
                            <q-checkbox dense v-model="props.selected" />
                          </q-td>
                          <q-td key="name" :props="props">{{ props.row.name }}</q-td>
                          <q-td key="code" :props="props">{{ props.row.code  }}</q-td>
                          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
                        </q-tr>
                        <q-tr v-show="props.expand" :props="props">
                          <q-td colspan="100%">
                          </q-td>
                        </q-tr>
                      </template>
                      <template v-slot:pagination="props">
                        <q-pagination
                          v-model="paginationField.page"
                          :max="pagesField"
                          :input="true"
                        >
                        </q-pagination>
                        共 {{ totalField }} 条
                      </template>
                    </q-table>
                  </q-step>
                </q-stepper>
              </div>
            </q-tab-panel>
          </q-tab-panels>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn v-if="!addOrEditForm.id" flat label="保存并分配权限" color="primary" :disable="loadingSave" :loading="loadingSingleSave" @click="saveSingleHandler">
            <q-tooltip anchor="top middle" self="bottom middle" :offset="[5, 5]" content-class="bg-black text-white">
              <div style="width:150px;font-size:11px">
                该操作会保存您在“角色属性”一栏填写的全部信息，并且不会关闭当前会话框，以便于您继续为该角色分配权限。
              </div>
            </q-tooltip>
          </q-btn>
          <q-space/>
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="保存" color="primary" :disable="loadingSingleSave" :loading="loadingSave" @click="saveHandler" v-show="addOrEditTab=='tab1'"/>
          <q-btn flat label="保存" color="primary" :disable="loadingSingleSave" :loading="loadingSave" @click="saveHandlerJur" v-show="addOrEditTab=='tab2'"/>
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { indexOf, filter } from 'lodash'
import { required } from 'vuelidate/lib/validators'
import { transformToTreeFormat } from 'src/utils/fns'
export default {
  name: 'Role',
  data () {
    return {
      searchToggle: false,
      searchForm: {
        name: '',
        code: '',
        createTime: ''
      },
      oneData: [],
      selected: [],
      visibleColumns: [
        'action',
        'name',
        'code',
        'createTime'
      ],
      // 当加入 required: true 属性时  visibleColumns 对当前字段无效
      columns: [
        { name: 'action', align: 'center', label: '操作' },
        { name: 'name', required: true, label: '角色名称', align: 'left', field: 'name', sortable: true },
        { name: 'code', required: true, label: '角色编码', align: 'left', field: 'code', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      data: [],
      total: 0,
      tableId: '',
      nodeSelected: '',
      nodeExpanded: [],
      pagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      // 最后发送的id
      selectMenu: [],
      step: 1,
      dataField: [],
      searchFormField: {
        roleName: '',
        roleCode: '',
        createTime: ''
      },
      totalField: '',
      selectedField: [],
      paginationField: {
        page: 1,
        rowsPerPage: 40,
        rowsNumber: 5,
        sortBy: '',
        descending: Boolean
      },
      dataButtom: [],
      searchFormButtom: {
        roleName: '',
        roleCode: '',
        createTime: ''
      },
      totalButtom: '',
      selectedButtom: [],
      paginationButtom: {
        page: 1,
        rowsPerPage: 40,
        rowsNumber: 5,
        sortBy: '',
        descending: Boolean
      },
      columnsField: [
        { name: 'name', required: true, label: '字段名称', align: 'left', field: 'name', sortable: true },
        { name: 'code', required: true, label: '字段编码', align: 'left', field: 'code', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      columnsButtom: [
        { name: 'name', required: true, label: '按钮名称', align: 'left', field: 'name', sortable: true },
        { name: 'code', required: true, label: '按纽编码', align: 'left', field: 'code', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      // dialog
      addOrEdit: 1, // 1 新增  2 修改
      loadingSave: false,
      loadingSingleSave: false,
      addOrEditDialog: false,
      maximizedToggle: false,
      addOrEditTab: 'tab1',
      addOrEditForm: {
        name: '',
        code: Number,
        defaultRole: 0
      },
      // tree
      nodes: [],
      nodeTicked: [],
      // 分配权限
      saveUserRoleGroupLoading: false, // 保存loding
      roleId: '',
      num: 0 // 判断第几次点击tab2
    }
  },
  computed: {
    pages () {
      return Math.ceil(this.total / this.pagination.rowsPerPage)
    },
    pagesButtom () {
      return Math.ceil(this.totalButtom / this.paginationButtom.rowsPerPage)
    },
    pagesField () {
      return Math.ceil(this.totalField / this.paginationField.rowsPerPage)
    },
    isNodeSelected () {
      return !!this.nodeSelected
    }
  },
  validations: {
    addOrEditForm: {
      name: { required },
      code: { required }
    }
  },
  watch: {
    'pagination.page' () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    },
    'addOrEditTab' () {
      if (this.num === 0) {
        this.getSelectTree()
        this.num++
      }
    },
    'step' () {
      if (this.tableId.length !== 0) {
        this.getTable()
      }
    },
    'nodeSelected' () {
      if (this.nodeSelected !== null) {
        this.tableId = this.nodeSelected
        this.getTable()
      }
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    // 回显
    getSelectTable () {
      let type = ''
      if (this.step === 1) {
        type = 1
      } else {
        type = -1
      }
      this.$api({
        method: 'post',
        url: `/mdm/rolepermission/query`,
        params: {
          roleId: this.roleId,
          typeIds: type,
          viewId: this.tableId
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.selectedField = []
          this.selectedButtom = []
          let ids = []
          if (this.step === 1) {
            data.forEach(item => {
              ids.push(item.permissionId)
            })
            console.log(ids)
            this.dataButtom.forEach(item => {
              if (ids.length === 0) {
                this.selectedButtom.push(item)
              } else {
                for (let i in ids) {
                  if (ids[i] === item.id) {
                    this.selectedButtom.push(item)
                  }
                }
              }
            })
          } else {
            data.forEach(item => {
              ids.push(item.permissionId)
            })
            console.log(ids)
            this.dataField.forEach(item => {
              if (ids.length === 0) {
                this.selectedField.push(item)
              } else {
                for (let i in ids) {
                  if (ids[i] === item.id) {
                    this.selectedField.push(item)
                  }
                }
              }
            })
            console.log(this.selectedField)
          }
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    // 回显菜单
    getSelectTree () {
      this.$api({
        method: 'post',
        url: `/mdm/rolepermission/query`,
        params: {
          roleId: this.roleId,
          typeIds: '0,2'
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          // this.nodeTicked
          console.log(data)
          let ticked = []
          data.forEach(item => {
            ticked.push(item.permissionId)
          })
          this.nodeTicked = ticked
          console.log(this.nodeTicked)
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    getParent (id) {
      for (let i in this.oneData) {
        if (this.oneData[i].id === id) {
          if (this.selectMenu.indexOf(this.oneData[i].id) === -1) {
            this.selectMenu.push(this.oneData[i].id)
          } if (this.oneData[i].parentId === 0) {
            break
          }
          this.getParent(this.oneData[i].parentId)
        }
      }
    },
    async saveHandlerJur () {
      // console.log(this.nodeTicked)
      // this.nodeTicked.forEach(item => {
      //   this.getParent(item)
      // })
      console.log(this.selectMenu)
      await this.$api({
        method: 'put',
        url: '/mdm/rolepermission/updateRoleViewPermissionList',
        params: {
          roleId: this.roleId,
          id: this.roleId,
          permissionIds: this.nodeTicked.join(','),
          code: this.addOrEditForm.code,
          // code: '0040',
          name: this.addOrEditForm.name,
          defaultRole: this.addOrEditForm.defaultRole
        },
        emulateJSON: true,
        useLoadLayer: true,
        useNotify: true,
        successCallback: ({ data }) => {
          console.log(data)
          this.nodeTicked = []
          this.selectedButtom = []
          this.selectedField = []
          this.addOrEditDialog = false
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    // 保存权限 字段/按钮
    async saveJurisdiction () {
      let type = ''
      let permissionIds = []
      if (this.step === 1) {
        type = 1
        this.selectedButtom.forEach(item => {
          permissionIds.push(item.id)
        })
      } else {
        type = -1
        this.selectedField.forEach(item => {
          permissionIds.push(item.id)
        })
      }
      this.saveUserRoleGroupLoading = true
      await this.$api({
        method: 'put',
        url: type === 1 ? '/mdm/rolepermission/updateRoleOperatePermissionList' : '/mdm/rolepermission/updateRoleColumPermissionList',
        params: {
          roleId: this.roleId,
          permissionIds: permissionIds.join(','),
          viewId: this.nodeSelected
        },
        emulateJSON: true,
        useLoadLayer: true,
        useNotify: true,
        successCallback: ({ data }) => {
          this.getSelectTable()
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.saveUserRoleGroupLoading = false
    },
    init () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    },
    async listGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        method: 'post',
        url: '/mdm/role/query',
        params: {
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.total = data.total
          this.data = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending
    },
    async add () {
      this.num = 0
      this.addOrEdit = 1
      this.addOrEditTab = 'tab1'
      this.addOrEditForm = {
        name: '',
        defaultRole: 0
      }
      this.ticked = []
      this.nodeTicked = []
      this.step = 1
      this.$v.addOrEditForm.$reset()
      await this.permissionGet()
      this.nodeSelected = ''
      this.addOrEditDialog = true
    },
    async edit (row) {
      this.roleId = row.id
      this.num = 0
      this.nodeSelected = ''
      this.nodeTicked = []
      await Promise.all([
        this.$api({
          method: 'get',
          url: `/mdm/role/findById/${row.id}`,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            this.addOrEditForm = { ...data }
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        }),
        this.permissionGet(),
        this.rolePermissionGet(row.id)
      ])
      this.addOrEditDialog = true
      this.addOrEdit = 2
      this.addOrEditTab = 'tab1'
      this.$v.addOrEditForm.$reset()
    },
    async saveHandler () {
      this.$v.addOrEditForm.$touch()
      console.log(this.addOrEditForm)
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSave = true
        await Promise.all([
          this.$api({
            method: 'put',
            url: this.addOrEdit === 1 ? '/mdm/role/add' : '/mdm/role/update',
            params: this.addOrEditForm,
            emulateJSON: true,
            useNotify: true,
            successCallback: ({ data }) => {
              this.addOrEditDialog = false
            },
            errorCallback (err) {
              console.log('未处理的业务级error：', err)
            }
          })
          // this.rolePermissionUpdate(this.addOrEditForm.id)
        ])
        this.loadingSave = false
        this.init()
      }
    },
    async saveSingleHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSingleSave = true
        await this.$api({
          method: 'put',
          url: '/mdm/role/add',
          params: this.addOrEditForm,
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.roleId = data.id
            this.nodeTicked = []
            this.addOrEditForm = { ...data }
            this.addOrEdit = 2
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSingleSave = false
        this.init()
      }
    },
    delRow (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除角色：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/mdm/role/delete/${row.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }).onCancel(() => {

      })
    },
    // 权限数据 获取
    permissionGet () {
      this.nodes = []
      this.$api({
        method: 'post',
        url: '/mdm/permission/query',
        params: {
          typeIds: '0,2'
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.oneData = data
          data.forEach(item => {
            // this.ids.push(item.id)
            if (item.type === 0) {
              item.header = 'root'
            } else if (item.type === 2) {
              item.header = 'header'
            }
          })
          this.nodes = transformToTreeFormat(data, 'id', 'parentId', 'children')
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    rolePermissionGet (id) {
      this.$api({
        method: 'post',
        url: '/mdm/rolepermission/query',
        params: {
          roleId: id
        },
        emulateJSON: true,
        successCallback: ({ data }) => {
          // this.ticked = data
          this.ticked = data.map(item => item.permissionId)
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    // 树形结构点击选中
    nodeSelectedClick (nodeSelected) {
      if (indexOf(this.nodeTicked, nodeSelected) > -1) {
        if (nodeSelected === this.nodeSelected) {
          this.nodeTicked = filter(this.nodeTicked, node => node !== nodeSelected)
        }
      } else {
        this.nodeTicked.push(nodeSelected)
      }
    },
    // rolePermissionUpdate (id) {
    //   this.$api({
    //     method: 'put',
    //     url: '/mdm/rolepermission/updateRolePermission',
    //     params: {
    //       permissionIds: this.ticked.join(','),
    //       roleId: id
    //     },
    //     emulateJSON: true,
    //     useNotify: true,
    //     successCallback: ({ data }) => {

    //     },
    //     errorCallback (err) {
    //       console.log('未处理的业务级error：', err)
    //     }
    //   })
    // },
    getTable () {
      let type = ''
      if (this.step === 1) {
        type = 1
      } else {
        type = -1
      }
      this.$api({
        method: 'post',
        url: `/mdm/permission/query`,
        params: {
          typeIds: type,
          parentId: this.tableId
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          console.log(this.step)
          if (this.step === 1) {
            this.dataButtom = data
            console.log(this.dataField)
          } else {
            this.dataField = data
          }
          this.getSelectTable()
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    }
  }
}
</script>
